package org.durcframework.autocode.generator.oracle;

import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.durcframework.autocode.generator.ColumnDefinition;
import org.durcframework.autocode.generator.ColumnSelector;
import org.durcframework.autocode.generator.DataBaseConfig;

public class OracleColumnSelector extends ColumnSelector{
	
	private static String TABKE_DETAIL_SQL = new StringBuilder()
			.append("SELECT ")
			.append("	T.COLUMN_NAME,")
			.append("	T.DATA_TYPE,")
			.append("	T.DATA_LENGTH,")
			.append("	T1.COMMENTS,")
			.append("	T.NULLABLE,")
			.append("	T2.COLUMN_NAME AS PRIMARY_KEY ")
			.append("FROM")
			.append("	ALL_TAB_COLUMNS T")
			.append("	LEFT JOIN USER_COL_COMMENTS T1 ON T1.TABLE_NAME = T.TABLE_NAME")
			.append("	LEFT JOIN USER_CONS_COLUMNS T2 ON T2.TABLE_NAME = T.TABLE_NAME ")
			.append("WHERE")
			.append("	T.table_name = '%s' ")
			.append("	AND T.OWNER = 'EDI_USER' ")
			.append("	AND T1.COLUMN_NAME = T.COLUMN_NAME ")
			.append("	AND T2.POSITION = 1 ")
			.append("ORDER BY	T.COLUMN_ID ASC")
			.toString();
			
	
	
	public OracleColumnSelector(DataBaseConfig dataBaseConfig) {
		super(dataBaseConfig);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected String getColumnInfoSQL(String tableName) {
		// TODO Auto-generated method stub
		return String.format(TABKE_DETAIL_SQL, tableName);
	}

	@Override
	protected ColumnDefinition buildColumnDefinition(Map<String, Object> rowMap) {
		Set<String> columnSet = rowMap.keySet();
		
		for (String columnInfo : columnSet) {
			rowMap.put(columnInfo.toUpperCase(), rowMap.get(columnInfo));
		}
		ColumnDefinition columnDefinition = new ColumnDefinition();
		String columnName= (String)rowMap.get("COLUMN_NAME");
		columnDefinition.setColumnName(columnName);
		String primaryKey = (String) rowMap.get("PRIMARY_KEY");
		if(StringUtils.equals(primaryKey, columnName)) {
			columnDefinition.setIsPk(true);
		}else {
			columnDefinition.setIsPk(false);
		}
		
		columnDefinition.setIsIdentity(false);
		columnDefinition.setType((String)rowMap.get("DATA_TYPE"));
		columnDefinition.setColumnSize(Integer.parseInt(rowMap.get("DATA_LENGTH")+""));
		columnDefinition.setComment((String)rowMap.get("COMMENTS"));
		String nullAble = (String)rowMap.get("COMMENTS");
		if(StringUtils.equals(nullAble, "Y")) {
			columnDefinition.setNull(false);
		}else {
			columnDefinition.setNull(true);
		}
		
		return columnDefinition;
	}

}
